package com.glink.manage.common.weather;

import com.alibaba.fastjson2.JSONObject;
import com.glink.manage.dto.weather.WeatherQueryPlaceNameDTO;
import com.glink.manage.vo.weather.WeatherGeneralVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by IntelliJ IDEA.
 * 万维易源
 * @Author : qiushaoshan
 * @create 2025/2/17 17:34
 */
@Slf4j
public class WeatherWanWeiYiYuan {

    // 查询天气
    private static final String URL_QUERY_WEATHER = "https://route.showapi.com/9-2";

    // 查询地名
    private static final String URL_QUERY_PLACE_NAME = "https://route.showapi.com/9-3";

    /**
     * 发送POST请求并返回响应结果
     *
     * @param appKey 应用的appKey
     * @param area   查询的地区
     * @return 响应结果字符串
     */
    public static WeatherGeneralVO queryPlaceName(String appKey, String area) {
        WeatherGeneralVO weatherGeneralVO = null;
        HttpURLConnection con = null;
        try {
            // 构建请求参数
            Map<String, String> params = new HashMap<>();
            params.put("appKey", appKey);
            params.put("area", URLEncoder.encode(area, StandardCharsets.UTF_8.toString()));

            // 创建URL对象
            URL obj = new URL(URL_QUERY_PLACE_NAME + "?" + toQueryString(params));
            con = (HttpURLConnection) obj.openConnection();

            // 设置请求方法为POST
            con.setRequestMethod("POST");

            // 设置请求头
            con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

            // 启用输入输出流
            con.setDoOutput(true);

            weatherGeneralVO = loadResultData(con);
        }catch (Exception e){
            log.error("万维易源 查询地址信息异常，url:{}, area:{}", URL_QUERY_PLACE_NAME, area, e);
        }finally {
            if(con != null){
                // 关闭连接
                con.disconnect();
            }
        }
       
        return weatherGeneralVO;
    }

    /**
     * 将Map中的参数转换为查询字符串
     *
     * @param params 参数Map
     * @return 查询字符串
     */
    private static String toQueryString(Map<String, String> params) {
        return params.entrySet().stream()
                .map(entry -> entry.getKey() + "=" + entry.getValue())
                .reduce((a, b) -> a + "&" + b)
                .orElse("");
    }

    /**
     * 地名-查询条件
     * @param placeNameDTO 查询条件
     * @return 天气信息
     */
    public static WeatherGeneralVO queryWeatherByPlaceName(WeatherQueryPlaceNameDTO placeNameDTO) {
        WeatherGeneralVO weatherGeneralVO = null;
        HttpURLConnection con = null;
        // 构建请求URL
        try {
            URL obj = new URL(URL_QUERY_WEATHER);
            con = (HttpURLConnection) obj.openConnection();

            // 设置请求方法为POST
            con.setRequestMethod("POST");

            // 设置请求头
            con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

            // 启用输入输出流
            con.setDoOutput(true);

            // 构建请求参数
            String appKey = placeNameDTO.getAppKey(); // 替换为你的appKey
            String areaCode = URLEncoder.encode(placeNameDTO.getAreaCode(), StandardCharsets.UTF_8.toString());
            String needMoreDay = URLEncoder.encode(placeNameDTO.getNeedMoreDay(), StandardCharsets.UTF_8.toString());
            String needIndex = URLEncoder.encode(placeNameDTO.getNeedIndex(), StandardCharsets.UTF_8.toString());
            String need3HourForcast = URLEncoder.encode(placeNameDTO.getNeed3HourForcast(), StandardCharsets.UTF_8.toString());
            String needAlarm = URLEncoder.encode(placeNameDTO.getNeedAlarm(), StandardCharsets.UTF_8.toString());
            String area = URLEncoder.encode(placeNameDTO.getArea(), StandardCharsets.UTF_8.toString());
            String needHourData = URLEncoder.encode(placeNameDTO.getNeedHourData(), StandardCharsets.UTF_8.toString());

            // 构建完整的POST数据
            String postData = String.format("appKey=%s&areaCode=%s&needMoreDay=%s&needIndex=%s&need3HourForcast=%s&needAlarm=%s&area=%s&needHourData=%s", appKey, areaCode, needMoreDay, needIndex, need3HourForcast, needAlarm, area, needHourData);

            // 发送POST请求
            try (OutputStream os = con.getOutputStream()) {
                byte[] input = postData.getBytes(StandardCharsets.UTF_8);
                os.write(input, 0, input.length);
            }

            return loadResultData(con);
        } catch (Exception e) {
            log.error("万维易源 查询天气信息异常，url:{}, placeNameDTO:{}", URL_QUERY_WEATHER, placeNameDTO, e);
            weatherGeneralVO = new WeatherGeneralVO();
            weatherGeneralVO.setShowapi_res_error(e.getMessage());
            return weatherGeneralVO;
        }finally {
            if(con != null){
                con.disconnect();    
            }
        }
    }

    /**
     * 装载返回结果
     *
     * @param con 连接信息
     * @return 返回结果
     * @throws IOException 异常信息
     */
    private static WeatherGeneralVO loadResultData(HttpURLConnection con) throws IOException {
        int responseCode = con.getResponseCode();
        WeatherGeneralVO weatherGeneralVO = null;
        if(responseCode == 200){
            System.out.println("Response Code: " + responseCode);
            // 读取响应
            StringBuilder response = new StringBuilder();
            try (BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()))) {
                String inputLine;
                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
            }
            String result = response.toString();
          
            if(StringUtils.isNotBlank(result)){
                try {
                    weatherGeneralVO = new WeatherGeneralVO();
                    weatherGeneralVO = JSONObject.parseObject(result, WeatherGeneralVO.class);
                } catch (Exception e) {
                    log.error("万维易源：  结果格式化异常：{}", result, e);
                }
            }
        }else{
            weatherGeneralVO = new WeatherGeneralVO();
            weatherGeneralVO.setShowapi_res_code(responseCode);
            weatherGeneralVO.setShowapi_res_error(con.getResponseMessage());
        }
        
        return weatherGeneralVO;
    }
}
